package com.chee.plant.server;

import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;

import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.IoSession;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.chee.plant.encrypt.Base64;
import com.chee.plant.encrypt.Des;
import com.chee.plant.log.LoggerFactory;
import com.chee.plant.log.PlantLogger;

/**
 * 这个类用作全局变量的访问，只能放入全局变量，细节类的内容不要放入
 * 
 *
 */
public class CommonData {
	private static IoAcceptor __acceptor;
	private static Configuration __hibernateConfig;
	private static SessionFactory __hibernateFactory;
	private static SessionServer __sessionServer;
	private static Des __des;
	private static Base64 __base64;
	private static String __desKey = "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest";
	private static Hashtable<IoSession,Long> __rawSessions;
	private static Hashtable<Integer,SessionEntity> __onlineUsers;
	static{
		__base64 = new Base64(); __des = new Des(__desKey);
		__rawSessions = new Hashtable<IoSession,Long>();
		__onlineUsers = new Hashtable<Integer, SessionEntity>();
		__sessionServer = new SessionServer();
		__hibernateConfig = new Configuration().configure();
		__hibernateFactory = __hibernateConfig.buildSessionFactory();
	}
	public static Configuration getHibernateConfig(){
		return __hibernateConfig;
	}
	public static SessionFactory getHibernateFactory(){
		return __hibernateFactory;
	}
	public static IoAcceptor getAcceptor(){
		return __acceptor;
	}
	public static void setAcceptor(IoAcceptor acceptor){
		__acceptor = acceptor;
	}
	/**
	 * Base64对象,完成Base64编码解码
	 * @return
	 */
	public static Base64 getBase64(){
		return __base64;
	}
	/**
	 * Des对象,完成Des加密解密
	 * @return
	 */
	public static Des getDes(){
		return __des;
	}
	/**
	 * 获取所有的在线用户
	 * @return
	 */
	public static Hashtable<Integer, SessionEntity> getOnlineUsers(){
		return __onlineUsers;
	}
	/**
	 * 获取操作Session的服务器
	 * @return
	 */
	public static SessionServer getSessionServer(){
		return __sessionServer;
	}
	/**
	 * 获取指定userId的session
	 * @param userId - 用户ID
	 * @return
	 */
	public static SessionEntity getSession(int userId){
		return __onlineUsers.get(userId);
	}
	/**
	 * 添加一个用户session
	 * @param session - 要添加的session
	 * @return
	 */
	public static boolean addSession(SessionEntity session){
		if(__onlineUsers.containsKey(session.getUserId())) return true;
		__onlineUsers.put(session.getUserId(), session);
		return true;
	}
	/**
	 * 从服务器去除指定用户的连接
	 * @param userId - 要从服务器去除连接的用户ID
	 * @return
	 */
	public static boolean removeSession(int userId){
		if(!__onlineUsers.containsKey(userId)) return true;
		SessionEntity entity = __onlineUsers.get(userId);
		if(entity != null) entity.close();
		__onlineUsers.remove(userId);
		return true;
	}
	/**
	 * 刷新用户的在线时间
	 * @param userId - 要刷新的用户ID
	 */
	public static void refreshUser(int userId){
		if(userId <= 0) return;
		SessionEntity sess = getSession(userId);
		if(sess == null) return;
		sess.refreshState();
	}
	/**
	 * 删除已经过期的用户连接
	 * @return
	 */
	public static boolean removeOverdueUser(){
		Collection<SessionEntity> coll = __onlineUsers.values();
		Iterator<SessionEntity> iter = coll.iterator();
		while (iter.hasNext()) {
			SessionEntity entry = iter.next();
			if (entry.isOverdue()){
				int userId = entry.getUserId();
				CommonData.removeSession(userId);
			}
			
		}
		return true;
	}
	/**
	 * 添加一个还未认证用户的session
	 * @param raw - 要添加的session
	 * @return
	 */
	public static boolean addRawSession(IoSession raw){
		if(__rawSessions.containsKey(raw)) return true;
		__rawSessions.put(raw, System.currentTimeMillis());
		return true;
	}
	/**
	 * 设置某个未认证用户session的userId
	 * @param raw - 要设置userId的session
	 * @param userId - 要设置的userId
	 * @return
	 */
	public static boolean setUserForRawSession(IoSession raw, int userId){
		if(!__rawSessions.containsKey(raw)) return false;
		Enumeration<IoSession> sessions = __rawSessions.keys();
		while(sessions.hasMoreElements()){
			IoSession sess = sessions.nextElement();
			if(sess.equals(raw)){
				SessionEntity entity = new SessionEntity(userId, raw);
				addSession(entity);
				removeRawSession(raw);
			}
		}
		return true;
	}
	/**
	 * 删除指定的未认证用户的session
	 * @param raw - 要删除的session
	 * @return
	 */
	public static boolean removeRawSession(IoSession raw){
		if(!__rawSessions.containsKey(raw)) return true;
		__rawSessions.remove(raw);
		return true;
	}
	/**
	 * 删除超时的未认证用户的session
	 * @return
	 */
	public static boolean removeOverdueRawSession(){
		Enumeration<IoSession> sessions = __rawSessions.keys();
		Long now = System.currentTimeMillis();
		while(sessions.hasMoreElements()){
			IoSession sess = sessions.nextElement();
			if(now - __rawSessions.get(sess) > 300000){
				sess.close();
				__rawSessions.remove(sess);
			}
		}
		return true;
	}
	/**
	 * 获取日志操作器
	 * @return
	 */
	public static PlantLogger getLogger(){
		return LoggerFactory.getLogger();
	}
	public static void log(String msg){
		System.out.println(msg);
	}
}
